package org.techmore.utils;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.os.Handler;
import android.os.Message;

public class DownloadNoStoreHandler implements Runnable{
	
	private String httpPath = null;
	private Handler progressHandler = null;
	private int sign = 0;
	
	public DownloadNoStoreHandler(String httpPath,Handler progressHandler,int sign){
		this.httpPath = httpPath;
		this.progressHandler = progressHandler;
		this.sign = sign;
	}
	public void run() {
		downLoadServiceObject(httpPath);
	}
	
	
	private void downLoadServiceObject(String httpPath) {
		InputStream fis = null;
		HttpURLConnection httpUrlConnection = null;
		StringBuffer sb = null;
		try {
			URL httpUrl = new URL(httpPath);
			httpUrlConnection = (HttpURLConnection) httpUrl.openConnection();
			int httpState = 404;
			try {
				httpState=httpUrlConnection.getResponseCode();
			} catch (ConnectException e) {
				e.printStackTrace();
			}
			if(httpState<400){
				httpUrlConnection.connect();
				fis = httpUrlConnection.getInputStream();
				sb = new StringBuffer();
				int i = 0;
				byte[] b = new byte[1024];
				
				while((i=fis.read(b)) != -1){
					sb.append(new String(b, 0, i));
				}
				sendMsg(sb.toString());
			}else{
				sendMsg("error");
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			try {
				if(fis != null){
					fis.close();
				}
				sb = null;
				httpUrlConnection.disconnect();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
//	private void parseXml(String xmlFile) {
//		if(xmlFile.length()>0){
//			try {
//				SAXParserFactory factory = SAXParserFactory.newInstance();
//				SAXParser parser = factory.newSAXParser();
//				parser.parse(xmlFile, defaultHandler);
//			} catch (ParserConfigurationException e) {
//				e.printStackTrace();
//			} catch (SAXException e) {
//				e.printStackTrace();
//			} catch (IOException e) {
//				e.printStackTrace();
//			}
//		}
//	}
	
	private void sendMsg(String flag) {
		Message msg = new Message();
		msg.what = sign;
		msg.obj = flag;
		progressHandler.sendMessage(msg);
	}
	
//	private File getImageCacheDirectory(){
////		if(!isSdcardPrepared()){
//			return new File(Environment.getDataDirectory(), PropertiesUtil.getInstance().getValue("qr_xml_file_cache"));
//		}else{
//			return new File(Environment.getExternalStorageDirectory(), "/service/com.techmore.pls/xmlCache");
//		}
//	}
	
//	private boolean isSdcardPrepared(){
//		return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
//	}

}
